<template>
  <div class="societyTextListOld">
    <div class="content">
      <div class="headerBgc" :style="{ background: `url(${imgbgc})`, 'background-size': '100% 100%' }">
        <div class="title">社会情境测验</div>
        <div class="typeBox">
          <span>测试日期：</span>
          <el-date-picker
            v-model="testTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </div>
      </div>
      <div class="questionBox">
        <div v-for="(item,index) in questionArr" :key="index" class="itemBox">
          <div class="selectItem" v-show="item.type == 'select' || item.type == 'checkbox'">
            <p>{{index + 1}}. {{item.questName}}</p>
            <span>被测人员选择了：</span>
            <el-select v-model="item.side" :multiple="item.type == 'checkbox'" :multiple-limit='3' filterable placeholder="请选择">
              <el-option
                v-for="row in item.extra1"
                :key="row"
                :label="'序号' + row"
                :value="row">
              </el-option>
            </el-select>
          </div>
          <div class="inputItem" v-show="item.type == 'input'">
            <p>{{index + 1}}. {{item.questName}}</p>
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="item.side">
            </el-input>
          </div>
          <div class="otherItem" v-show="item.type == 'secondSelect'">
            <p>{{index + 1}}. {{item.questName}}</p>
            <el-select v-model="selectValue" @change="selectChangeFn" placeholder="请选择">
              <el-option label="会" value="会"></el-option>
              <el-option label="不会" value="不会"></el-option>
            </el-select>
            <div v-show="selectValue=='会'">
              <div style="margin:20px 0">
                <span>请重新选择：</span>
                <el-select v-model="anginSelect" multiple :multiple-limit='3' filterable placeholder="请选择">
                  <el-option
                    v-for="row in 46"
                    :key="row"
                    :label="'序号' + row"
                    :value="row">
                  </el-option>
                </el-select>
              </div>
              <p>您为什么改变选择?</p>
              <el-input
                type="textarea"
                :rows="4"
                placeholder="请输入内容"
                v-model="againSide">
              </el-input>
            </div>
            <div v-show="selectValue=='不会'" style="margin:20px 0">
              <p>您为什么不改变选择?</p>
              <el-input
                type="textarea"
                :rows="4"
                placeholder="请输入内容"
                v-model="againSide">
              </el-input>
            </div>
          </div>
        </div>
        <div class="btn">
          <el-button type="primary" size="large" v-show="type!='edit'" @click="finishFn">完成</el-button>
          <el-button type="primary" size="large" v-show="type=='edit'" @click="saveFn">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { seckGetQuestions, seckAddAssessRecord, seckUpdateAssessRecord } from '@/api/home.js'
export default {
  data() {
    return {
      imgbgc: require('../../assets/images/phbgc.png'),
      personType: 'adult',
      testTime: new Date(),
      itemname: '',
      questionArr: [
        // {
        //   questName: '请从下面图片中选出一张您和父亲相处模式最像的一张图片。',
        //   type: 'select',
        //   side: ''
        // },
        // {
        //   questName: '请问您为什么选择这张图片?',
        //   type: 'input',
        //   side: ''
        // },
        // {
        //   questName: '请问图片中哪个代表您？',
        //   type: 'input',
        //   side: ''
        // },
        // {
        //   questName: '请您描述一下图片中两人（团体）的关系怎么样？?',
        //   type: 'input',
        //   side: ''
        // },
        // {
        //   questName: '请您再选择一张与您当前关系相反的图片。',
        //   type: 'select',
        //   side: ''
        // },
        // {
        //   questName: '请问您觉得这两张图片主要有什么不同或差异？?',
        //   type: 'input',
        //   side: ''
        // }
      ],
      testType: '',
      whichQuestion: '3',
      type: '',
      recordId: '',
      selectValue: '',
      anginSelect: '',
      againSide: '',
      WAIMS_TOKEN: ''
    }
  },
  mounted() {
    if(localStorage.getItem('WAIMS_TOKEN') && localStorage.getItem('WAIMS_TOKEN') !== '') {
      this.WAIMS_TOKEN = localStorage.getItem('WAIMS_TOKEN')
      this.type = this.$route.query.type ? this.$route.query.type : ''
      this.recordId = this.$route.query.recordId ? this.$route.query.recordId : ''
      this.questionArr = this.$route.query.questionArr ? JSON.parse(this.$route.query.questionArr) : []
      // 二次筛选的回显
      for(var i in this.questionArr) {
        if(this.questionArr[i].type === 'secondSelect') {
          // ['会', '6,5,4', '222']   ['不会', '222']
          var temparr = this.questionArr[i].side.split(';')
          this.selectValue = temparr[0]
          if (this.selectValue === '会') {
            this.anginSelect = temparr[1].split(',')
            this.againSide = temparr[2]
          } else {
            this.anginSelect = ''
            this.againSide = temparr[1]
          }
        }
      }
      console.log(this.anginSelect)
      this.itemname = this.$route.query.itemname ? this.$route.query.itemname : ''
      this.testType = this.$route.query.testType ? this.$route.query.testType : ''
      this.testTime = this.$route.query.testTime ? this.$route.query.testTime : new Date()
      if(this.type !== 'edit') {
        this.getquestFn()
      }
    } else {
      // 清除localStorage 跳出网站
      // 清除与登录信息相关的local storage
      localStorage.removeItem("isLogin");
      localStorage.removeItem("baseInfo");
      localStorage.removeItem("proInfo");
      localStorage.removeItem("proUserFile");
      localStorage.removeItem("generalUserInfo");
      localStorage.removeItem("testId");
      // 清除session storage
      sessionStorage.clear();
      // 删除保存在cookie里的token
      document.cookie = "WAIMS_TOKEN" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
      if(window.location.href.indexOf('https://xn--15t241ax9eqv8a.xn--fiqs8s/psych') > -1 ) {
        window.location.href = "https://xn--15t241ax9eqv8a.xn--fiqs8s/"
      } else if (window.location.href.indexOf('https://psychological-assessment.com/psych') > -1 ) {
        // 测试环境
        window.location.href = 'https://psychological-assessment.com/'
      } else {
        // 正式环境
        window.location.href = 'https://psychometrics-home.com/'
      }
    }
    this.personType = sessionStorage.getItem('personType')
    if(this.personType == 'adult') {
      this.imgbgc = require('../../assets/images/phbgc.png')
    } else {
      this.imgbgc = require('../../assets/images/chbgc.png')
    }
  },
  methods: {
    formatDateTime (date) {
      var y = date.getFullYear();
      var M = date.getMonth() + 1;
      M = M < 10 ? ('0' + M) : M;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      var mm = date.getMinutes();
      mm = mm < 10 ? ('0' + mm) : mm;
      return y + '-' + M + '-' + d+' '+h+':'+mm;
      // return y + '-' + m + '-' + d
    },
    selectChangeFn() {
      this.anginSelect = ''
      this.againSide = ''
    },
    finishFn() {
      // if(this.testTime == null || this.testTime == '') {
      //   this.testTime = this.formatDateTime(new Date())
      // } else {
      //   this.testTime = this.formatDateTime(this.testTime)
      // }
      // 处理问题中二次选择传值
      for(var i in this.questionArr) {
        if(this.questionArr[i].type === 'secondSelect') {
          if (this.selectValue === '会') {
            this.questionArr[i].side = this.selectValue + ';' + this.anginSelect + ';' + this.againSide
          } else {
            this.questionArr[i].side = this.selectValue + ';' + this.againSide
          }
        }
      }
      console.log(this.questionArr)
      var query = {
        testedId: sessionStorage.getItem('testedId'),
        whichQuestion: this.whichQuestion, // 分测验名称 1: 双人关系测验 2: 家庭或团体测验 3: 社会情境测验
        extra2: this.itemname, // 分测验对象
        result: JSON.stringify(this.questionArr),
        testTime: (this.testTime == null || this.testTime == '') ? new Date() : this.testTime // 测试时间
      }
      seckAddAssessRecord(query).then(res => {
        if(res.code === 200) {
          var temparr = this.testType.split(',')
          // 由小到大排序
          temparr = temparr.sort().filter(item=> item)
          if(temparr.length>0) {
            this.$router.push({
              path: temparr[0] === '1'?'/doubleText':(temparr[0] === '2'?'/familyText':'/societyTextListOld'),
              query: {
                testType: temparr.slice(1).join(',')
              }
            })
          } else {
            // 所有测验完毕，跳转到当前用户的测验列表
            this.$router.push({
              path: '/personList',
              query: {
                type: 'look'
              }
            })
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    saveFn() {
      // 处理问题中二次选择传值
      for(var i in this.questionArr) {
        if(this.questionArr[i].type === 'secondSelect') {
          if (this.selectValue === '会') {
            this.questionArr[i].side = this.selectValue + ';' + this.anginSelect + ';' + this.againSide
          } else {
            this.questionArr[i].side = this.selectValue + ';' + this.againSide
          }
        }
      }
      console.log(this.questionArr)
      console.log(this.anginSelect)
      var query = {
        WAIMS_TOKEN: this.WAIMS_TOKEN,
        // testId: 10008,
        recordId: this.recordId,
        result: JSON.stringify(this.questionArr),
        testTime: (this.testTime == null || this.testTime == '') ? new Date() : this.testTime // 测试时间
      }
      seckUpdateAssessRecord(query).then(res => {
        if(res.code === 200) {
          this.$router.push({
            path: '/personList',
            query: {
              type: 'look'
            }
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getquestFn() {
      var query = {
        group: '3', // 社会情境
        itemName: this.itemname
      }
      seckGetQuestions(query).then(res => {
        if(res.code === 200) {
          this.questionArr = res.data
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.societyTextListOld {
  height: 100vh;
  .content {
    position: relative;
  }
  .headerBgc {
    height: 300px;
    background: url(../../assets/images/phbgc.png) no-repeat;
    background-size: cover 100%;
    border-bottom-right-radius: 70px;
    border-bottom-left-radius: 70px;
    color: #fff;
    padding: 100px 0 0 300px;
    .name {
      font-size: 32px;
      font-weight: 700;
      margin-bottom: 10px;
    }
    .title {
      font-size: 32px;
      font-weight: 700;
      margin-bottom: 20px;
    }
    .typeBox {
      font-size: 30px;
    }
  }
  .questionBox {
    position: absolute;
    top: 300px;
    left: 50%;
    margin-left: -600px;
    .itemBox {
      background-color: #ffffff;
      box-shadow: 0px 0px 20px 0px rgb(0 0 0 / 20%);
      border-radius: 40px;
      width: 1000px;
      margin-bottom: 30px;
      padding: 40px 100px;
    }
    .selectItem, .inputItem, .otherItem {
      margin-bottom: 20px;
      p {
        margin-bottom: 15px;
      }
    }
    .selectItem {}
    .inputItem {}
  }
  .btn {
    margin-left: 520px;
    margin-bottom: 40px;
  }
}
</style>

<style lang="scss">
.societyTextListOld {
  .el-select {
    width: 280px;
  }
}
</style>